var ws = new WebSocket("wss://" + location.host + "/call");
var video;
var viewerID;
var webRtcPeer;

// 页面加载
window.onload = function () {
  video = document.getElementById("video");
  viewerID = document.getElementById("viewID");

  // 发起视频
  presenter();

  // 播放视频
  viewer();
};

// onbeforeunload 事件在即将离开当前页面（刷新或关闭）时触发。
window.onbeforeunload = function () {
  // 在页面刷新或离开时，关闭socket实例
  ws.close();
};

ws.onmessage = function (message) {
  var parsedMessage = JSON.parse(message.data);
  console.info("Received message: " + message.data);

  switch (parsedMessage.id) {
    case "presenterResponse":
      presenterResponse(parsedMessage);
      break;
    case "viewerResponse":
      viewerResponse(parsedMessage);
      break;
    case "iceCandidate":
      webRtcPeer.addIceCandidate(parsedMessage.candidate, function (error) {
        if (error) return console.error("Error adding candidate: " + error);
      });
      break;
    case "stopCommunication":
      dispose();
      break;
    default:
      console.error("Unrecognized message", parsedMessage);
  }
};

function presenterResponse(message) {
  if (message.response != "accepted") {
    var errorMsg = message.message ? message.message : "Unknow error";
    console.info("Call not accepted for the following reason: " + errorMsg);
    dispose();
  } else {
    webRtcPeer.processAnswer(message.sdpAnswer, function (error) {
      if (error) return console.error(error);
    });
  }
}

function viewerResponse(message) {
  if (message.response != "accepted") {
    var errorMsg = message.message ? message.message : "Unknow error";
    console.info("Call not accepted for the following reason: " + errorMsg);
    dispose();
  } else {
    webRtcPeer.processAnswer(message.sdpAnswer, function (error) {
      if (error) return console.error(error);
    });
  }
}

function onIceCandidate(candidate) {
  console.log("Local candidate" + JSON.stringify(candidate));

  var message = {
    id: "onIceCandidate",
    candidate: candidate,
  };
  sendMessage(message);
}

// 播放接听方视频
function viewer() {
  if (!webRtcPeer) {
    showSpinner(viewerID);
    var options = {
      remoteVideo: viewerID,
      onicecandidate: onIceCandidate,
    };
    webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerRecvonly(
      options,
      function (error) {
        if (error) {
          return console.error(error);
        }
        this.generateOffer(onOfferViewer);
      }
    );

    // enableStopButton();
  }
}

function onOfferViewer(error, offerSdp) {
  if (error) {
    return console.error("Error generating the offer");
  }
  console.info("Invoking SDP offer callback function " + location.host);
  var message = {
    id: "viewer",
    sdpOffer: offerSdp,
  };
  sendMessage(message);
}

// 发起视频会议
function presenter() {
  if (!webRtcPeer) {
    showSpinner(video);

    var options = {
      localVideo: video,
      onicecandidate: onIceCandidate,
    };
    webRtcPeer = new kurentoUtils.WebRtcPeer.WebRtcPeerSendonly(
      options,
      function (error) {
        if (error) {
          return console.error(error);
        }
        webRtcPeer.generateOffer(onOfferPresenter);
      }
    );

    // 挂断
    // enableStopButton();
  }
}

function onOfferPresenter(error, offerSdp) {
  if (error) {
    return console.error("Error generating the offer");
  }
  console.info("Invoking SDP offer callback function " + location.host);
  var message = {
    id: "presenter",
    sdpOffer: offerSdp,
  };
  sendMessage(message);
}

// 发送消息？
function sendMessage(message) {
  var jsonMessage = JSON.stringify(message);
  console.log("Sending message: " + jsonMessage);
  ws.send(jsonMessage);
}

// 显示加载中gif
function showSpinner() {
  for (var i = 0; i < arguments.length; i++) {
    arguments[i].poster = "./img/transparent-1px.png";
    arguments[i].style.background =
      'center transparent url("./img/spinner.gif") no-repeat';
  }
}

// 隐藏gif
function hideSpinner() {
  for (var i = 0; i < arguments.length; i++) {
    arguments[i].src = "";
    arguments[i].poster = "./img/webrtc.png";
    arguments[i].style.background = "";
  }
}

function dispose() {
  if (webRtcPeer) {
    webRtcPeer.dispose();
    webRtcPeer = null;
  }
  hideSpinner(video, viewID);

  // disableStopButton();
}
